package com.wink_172.library.activity

import android.content.Context
import org.greenrobot.eventbus.EventBus;
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.fragment.app.FragmentActivity
import com.hjq.language.MultiLanguages
import com.wink_172.library.AppManager
import com.wink_172.library.R
import com.wink_172.library.model.json.CustomEventBus
import com.wink_172.library.view.CustomProgressDialog
import com.wink_172.library.view.ProgressLoading
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

open class SmartActivity : FragmentActivity(), View.OnClickListener {
    open  var progressDialog: CustomProgressDialog? = null
    open  var mCallback: ICallback? = null
   open var mode:Int=0;//模式
    open var activity=this;
    override fun onClick(v: View) {}
    interface ICallback {
        fun onSendEvent(event: Int,vararg args: Any?)
    }



    /**
     * 使用方法1
     * **/
//    val callback=object:
//        SmartActivity.ICallback {
//        override fun onSendEvent(event: Int, vararg args: Any?) {//这个callback用的非常巧妙
//            when (event) {
//
//            }
//        }
//    }

    /**
     * 使用方法2
     *
     * */
//    object :
//        SmartActivity.ICallback {
//        override fun onSendEvent(event: Int,vararg args: Any?) {//这个callback用的非常巧妙
//
//        }
//    }

    public override fun attachBaseContext(newBase: Context) {
        // 国际化适配（绑定语种）
        super.attachBaseContext(MultiLanguages.attach(newBase))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //        setContentView(R.layout.activity_smart);

        Log.e("onCreate","savedInstanceState:"+savedInstanceState);
        if(savedInstanceState!=null){

        }
        if (Build.VERSION.SDK_INT >= 21) {
//            windowTranslucentStatus这个属性会和setStatusBarColor、键盘顶起等属性冲突,后期请注意这个地方
//            getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        }

//        setStatusBarLightMode();
        AppManager.appManager?.addActivity(this);
        handler = MyHandler()


        EventBus.getDefault().register(this)
    }


    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @Subscribe(threadMode = ThreadMode.MAIN)
   open fun onGetMessages(messageBus: CustomEventBus) {

        when(messageBus.type){

        }
    }

    /**
     * 请不要再外部调用MyHandler().sendMessage
     * 它是每调用一次就生成一个新的handler   不是同一个handler 根本removeMessages不了
     * 请使用getHandle()方法
     * */
    fun getHandle():MyHandler{
        return handler!!;
    }

    override fun onDestroy() {
        super.onDestroy()
        AppManager.appManager?.finishActivity(this);
        EventBus.getDefault().unregister(this)
    }


    open  fun requestPermissions(requestCode: Int, permissions: Array<String>) {
        if (permissions != null && permissions.size > 0) {
            ActivityCompat.requestPermissions(this, permissions, requestCode)
        }
    }
    open  fun checkPermissions(permissions: Array<String>?): Boolean {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true
        }
        val remains = ArrayList<String>()
        if (permissions != null) {
            for (permission in permissions) {
                if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
                    continue
                }
                remains.add(permission)
            }
        }
        return remains.size == 0
    }

    /**
     * 这个要利用好 在样式上面有许多用处的 下面两个点要利用好   args: Any传递两个color
     * 1. color1 = resources.getColor(R.color.transparent)
     *    color2 = R.color.transparent
     * 2.setBackgroundDrawableResource   可设置activity背景完全透明
     * */
   open fun setStatusBarLightMode(vararg args: Any) {
        var color1 = resources.getColor(R.color.white)   //bar颜色
        var color2 =R.color.white   //activity背景颜色
        if (args != null && args.size >=2) {
            color1 = args[0] as Int //自定义颜色 res   resources.getColor(R.color.transparent)
            color2 = args[1] as Int //自定义颜色 resid    R.color.transparent
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //判断是否为小米或魅族手机，如果是则将状态栏文字改为黑色
//            if (MIUISetStatusBarLightMode(activity, true) || FlymeSetStatusBarLightMode(activity, true)) {
//                //设置状态栏为指定颜色
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0
//                    activity.getWindow().setStatusBarColor(color);
//                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4
//                    //调用修改状态栏颜色的方法
//                    setStatusBarColor(activity, color);
//                }
//            } else
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //如果是6.0以上将状态栏文字改为黑色，并设置状态栏颜色
                window.setBackgroundDrawableResource(color2)
                window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                window.statusBarColor = color1

                //fitsSystemWindow 为 false, 不预留系统栏位置.
                val mContentView = window.findViewById<View>(Window.ID_ANDROID_CONTENT) as ViewGroup
                val mChildView = mContentView.getChildAt(0)
                if (mChildView != null) {
                    ViewCompat.setFitsSystemWindows(mChildView, true)
                    ViewCompat.requestApplyInsets(mChildView)
                }
            }
        }
    }

    /**
     * args[0] 外部可点击消失
     *    args[1] 文字
     *    args[2] 背景
     * */
    open fun showProgressDialog(vararg args: Any?) {
        if (progressDialog == null) {
            progressDialog = CustomProgressDialog(this, R.style.CustomProgressDialog)

            progressDialog!!.setContentView(R.layout.progress_loading)
            progressDialog!!.show()

            val progress_loading=progressDialog!!.findViewById<View>(R.id.progress_loading) as ProgressLoading
            progress_loading.tv_message.visibility=View.GONE

            var touch = false

            if (args != null) {
                when( args.size){
                    1->{
                       touch = args[0] as Boolean

                    }
                    2->{
                        touch = args[0] as Boolean
                        val str_text = args[1] as String

                        progress_loading.tv_message.setText(str_text)
                        progress_loading.tv_message.visibility=View.VISIBLE
                    }
                    3->{
                        touch = args[0] as Boolean
                        val str_text = args[1] as String
                        val show_bg = args[2] as Boolean

                        progress_loading.tv_message.setText(str_text)
                        progress_loading.tv_message.visibility=View.VISIBLE

                        Log.e(TAG, "showProgressDialog: ====>>"+args.size +"  str_text:"+str_text)
                        if(show_bg){
                            progress_loading.background=activity!!.resources.getDrawable(R.drawable.toaststyle)
                        }
                    }
                }


            }
            progressDialog!!.setCancelable(touch)
            progressDialog!!.setCanceledOnTouchOutside(touch)
            progressDialog!!.window!!.attributes.gravity = Gravity.CENTER

        } else {
            progressDialog!!.show()
        }
    }

    open fun hideProgressDialog() {
        if (progressDialog != null&&activity!=null&&activity.isFinishing==false) {
            progressDialog!!.dismiss()
            progressDialog = null
        }
    }

    open var handler: MyHandler? = null

    inner class MyHandler : Handler() {
        override fun handleMessage(msg: Message) {
            handlerCallBack(msg)
        }
    }

    open fun handlerCallBack(msg: Message?) {}


    companion object {
        private const val TAG = "TAG"
    }
}